//评论类
function NewComment(option){
    var option = option || {};
    this.getCommentUrl = option.getCommentUrl || '/btcomment/';
    this.setCommentUrl = option.setCommentUrl || '/btcomment/';
    this.commentForm = option.commentForm || $('#comment-form');
    this.commentCount = option.commentCount || $("#comments-count");
    this.commentList = option.commentList || $('#comments-list');
    this.loading = option.loading || $("#comments-loading");
    this.commentTextArea = option.commentTextArea || $("#comment-area");
    this.commentTextAreaShadow = this.commentTextArea.prev();
    this.isSubmitting = false;
    this.isFocus = false;

    this._init();
}

NewComment.prototype = {
    _init : function(){
        var _self = this;

        this.commentList.on('swipeLeft', 'li', this._readyToDelete());
        
        this.commentTextArea.on('change', function(e){
            _self.autoExpand();
        }).on('keydown', function(e){
            _self.autoExpand();
            var _this = $(this);
            setTimeout(function(){
                if(!_this.val()){
                    _self.commentForm.find('input[name="reply_to_comment_id"]').val("");
                }
            },10);
            
        }).on('focus',function(e){
            _self.isFocus = true;
            _self.loading.hide();
            _self.commentForm.parent().addClass('focus');
            _self.commentForm.parents('.m-new-comment').addClass('focus');
            _self.commentTextArea.focus();
        }).on('blur',function(e){
            _self.isFocus = false;
            _self.loading.show();
            _self.commentForm.parent().removeClass('focus');
            _self.commentForm.parents('.m-new-comment').removeClass('focus');
        });

        this.commentForm.on('submit', this.postComment());
        this.commentList.on('click', 'li', this.replyComment());
        this.commentList.on('click', '.delete', this.deleteComment());

        $(document).on('scroll',function(){
            if(_self.commentList.offset().top < $(window).scrollTop() + $(window).height()){
                _self.commentForm.parent().addClass("show");
            }else{
                _self.commentForm.parent().removeClass("show");
            }
        });
      
    },
    autoExpand : function(){
        var _self = this;
        _self.commentTextAreaShadow.val(_self.commentTextArea.val());
        setTimeout(function(){
            if(_self.commentTextAreaShadow.get(0).scrollHeight > 76 ){
                return;
            }
            var maxHeight = Math.max(_self.commentTextAreaShadow.get(0).scrollHeight,32);
            _self.commentTextArea.css('height', maxHeight + "px"); 
            if(maxHeight > 32){
                _self.commentTextArea.parent().addClass('auto-height');
            }else{
                _self.commentTextArea.parent().removeClass('auto-height');
            }
            
        },0);
    },
    deleteComment: function(){
        _self = this;
        return function(e){
            e.preventDefault();
            if ( BT.context('comment_is_staff') ) {
                result = window.confirm('这么就删除了？');
                if ( !result ) {
                    return false;
                }
            }
            var _li = $(this).parents('li'),
                _id = _li.data('cid');
            $.ajax({
                url: _self.setCommentUrl,
                type: 'POST',
                dataType: 'json',
                data: {
                    operator: 'delete',
                    csrfmiddlewaretoken: BT.context('comment_csrf_token'),
                    id: _id
                },
                success: function (data) {
                    if ( data.success ) {
                        $(_li).fadeOut('500');
                        _self._modifyCount( -1 );
                    }else{
                        alert(data.errmsg);
                    }
                }
            });
        }
    },
    postComment : function(){
        var _self = this;
        return function(e){
            e.preventDefault();
            if(_self.isSubmitting){
                return;
            }
            _self.isSubmitting = true;
            if(!BT.context('comment_user_id') || BT.context('comment_user_id') == 'null'){
                btAppSchema.jumpToLogin(window.location.href);
            }else{
                var _data = $(this).serializeArray();
                $.ajax({
                    url: _self.setCommentUrl,
                    type: 'POST',
                    dataType: 'json',
                    data: _data,
                    success: function (data) {
                        if ( data.success ) {
                            _self.commentTextArea.val('');
                            _self.commentTextArea.css('height', "32px");
                            
                            $(_self._buildCommentHtml(data.comment)).prependTo(_self.commentList);
                            $(window).scrollTop(_self.commentList.parent().offset().top);

                            _self._modifyCount( 1 );
                            _self.commentForm.find('input[name="reply_to_comment_id"]').val('');
                            if ( data.point_message ) {
                                btAppSchema.showFormattedNotification(data.point_message);
                            }
                        }
                        _self.isSubmitting = false;
                    },
                    error: function(){
                        _self.isSubmitting = false;
                    }
                });
            }
        }

    },
    replyComment : function(){
        var _self = this;
        return function(e){
            var target = $(e.target),
                _this = $(this);
            if( target.hasClass('avatar') || target.hasClass('comment-username') || e.target == _this.find('.avatar img').get(0) ){
                return;
            }
            e.preventDefault();
            if(_this.find('.delete').hasClass('show') ){
                _this.find('.delete').removeClass('show');
                return;
            }
            if(_this.find('.reply').length > 0){
                if(!BT.context('comment_user_id') || BT.context('comment_user_id') == 'null'){
                    btAppSchema.jumpToLogin(window.location.href);
                }else{
                    var _name = _this.find('.comment-username').html();
                        comment_id = _this.data('cid');
                    _self.commentTextArea.focus().val('回复'+_name);
                    // _self.commentForm.get(0).scrollIntoView();
                    _self.commentForm.find('input[name="reply_to_comment_id"]').val(comment_id);
                }
            }
        }
    },
    _readyToDelete: function(e){
        return function(e){
            $(this).find('.delete').addClass('show');
        }
    },
    _modifyCount : function(count){
        var commentCount = this.commentCount;
        var num = parseInt( commentCount.text() ) + count;
        commentCount.text(num);
    },
    _loadMoreComments : function(){
        var _self = this;
        this.loadHandeler = this.loadHandeler || function(e){
            var reachBottom = document.body.scrollTop + window.innerHeight >= $(document).height() - 200;
            if ( reachBottom && !_self.isFocus) {
                $(document).off('scroll',_self._loadMoreComments());
                _self.getComments();
            }
        }
        return this.loadHandeler;
    },
    getComments : function(){
        var _self = this;
        $.ajax({
            url: _self.getCommentUrl,
            type: 'GET',
            dataType: 'json',
            data: {
                'uri': BT.context('comment_bt_comment_uri'),
                'count': 10,
            },
            success: function (data) {
                if ( data.success ) {
                    _self.getCommentUrl = data.next_page_url;
                    _self.commentCount.text(data.total);
                    $.each(data.comments, function(index, val) {
                
                        $(_self.loading).before(_self._buildCommentHtml(val));
                    });
                    if ( data.has_more ) {
                        $(document).on('scroll', _self._loadMoreComments());
                    }else{
                        $(document).off('scroll',_self._loadMoreComments());
                        _self.loading.remove();
                    }
                }
            },
        });
    },
    _buildCommentHtml : function(comment){
        var html = [
            '<li class="clearfix" data-cid="'+comment.comment_id+'">',
                '<a href="javascript:btAppSchema.jumpToUser('+comment.user_id+', \''+comment.username+'\');" class="avatar">',
                    '<img src="'+comment.user_avatar+'">',
                '</a>',
                ( BT.context('comment_user_id') == comment.user_id || BT.context('comment_is_staff') ? '<span class="delete">X</span>' : '' ),
                '<div class="comment-info">',
                    '<a class="comment-username" href="javascript:btAppSchema.jumpToUser('+comment.user_id+', \''+comment.username+'\');">'+comment.username+':</a>',
                    NewComment.encodeHTML(comment.comment),
                '</div>',
                '<div class="comment-other">',
                    '<span class="comment-time">'+comment.date_added+'</span>',
                    ( BT.context('comment_user_id') == comment.user_id ? '' : '<span class="reply">回复</span>' ),
                '</div>',
            '</li>'
        ];
        return html.join('');
    }
}
NewComment.encodeHTML = function(source) {                                                                                                                
    return String(source)
        .replace(/&/g,'&amp;')
        .replace(/</g,'&lt;')
        .replace(/>/g,'&gt;')
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#39;");
}

window.BT = window.BT || {};
BT.NewComment = NewComment;